package pf.springBoot.springBootSSO.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import pf.java.pfHelperNotSpring.FuncAuthorityClass;
import pf.java.pfHelper.config.PFDataHelper;
import pf.springBoot.springBootSSO.oAuth.FormsAuth;

public class AutoLoginInterceptor implements HandlerInterceptor {

    private String _action = null;
    private FuncAuthorityClass _funcAuthority = FuncAuthorityClass.Default;
//    @Autowired
//    private AdminUserService adminUserService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证权限
        if (this.hasPermission(request,handler)) {
            return true;
        }
//        //  null == request.getHeader("x-requested-with") TODO 暂时用这个来判断是否为ajax请求
//        // 如果没有权限 则抛403异常 springboot会处理，跳转到 /error/403 页面
        //response.sendError(HttpStatus.FORBIDDEN.value(), "无权限");
        
//        response.setCharacterEncoding(PFDataHelper.encoding);
//        response.getWriter().write("无权限");
        
        request.setCharacterEncoding(PFDataHelper.encoding);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write( "你没有访问此功能的权限，请联系管理员！");

        return false;
    }
 
    /**
     * 是否有权限
     *
     * @param handler
     * @return
     */
    private boolean hasPermission(HttpServletRequest request,Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            MvcMenuFilter requiredPermission = handlerMethod.getMethod().getAnnotation(MvcMenuFilter.class);
            // 如果方法上的注解为空 则获取类的注解
            if (requiredPermission == null) {
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(MvcMenuFilter.class);
            }
//            ElementType.METHOD
//            boolean annotationPresent = method.isAnnotationPresent(Login.class);
            // 如果标记了注解，则判断权限
            if (requiredPermission != null 
//            		&&StringUtils.isNotBlank(requiredPermission.value())
            		) {
            	
            	if(!PFDataHelper.StringIsNullOrWhiteSpace(requiredPermission.value())) {
            		_action=requiredPermission.value();
            	}
                // redis或数据库 中获取该用户的权限信息 并判断是否有权限
            	String authorizeCode = GetAuthorizeCode(request);
            	Map<String, FuncAuthorityClass> funcAuthorities = FormsAuth.GetFuncAuthorities();

                if (funcAuthorities != null &&PFDataHelper.MapAny( funcAuthorities,a -> a.getKey() == authorizeCode && a.getValue().HasFlag(_funcAuthority)))
                {
//                    filterContext.Controller.ViewData["authorities"] = funcAuthorities[authorizeCode];//benjamin todo
                }
                else//分公司跨平台AutoLogin时由于funcAuthorities为空，所以会进入此判断。但这样就表示，只要没加AllowAnonymousAttribute，分公司就一定不能访问存在MvcMenuFilter的功能？
                {
                	return false;
                	
                	//benjamin todo
//                    Boolean skipAuthorization = PFDataHelper.AllowAutoLogin()?
//                        (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
//                                             || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true))
//                                             :false;
//                    if (!skipAuthorization) { filterContext.Result = new ContentResult() { Content = "你没有访问此功能的权限，请联系管理员！" }; }
//                    
                }
                
//                Set<String> permissionSet = adminUserService.getPermissionSet();
//                if (CollectionUtils.isEmpty(permissionSet) ){
//                    return false;
//                }
//                return permissionSet.contains(requiredPermission.value());
            }
        }
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // TODO
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO
    }
    
//    public String GetAuthorizeCode(RouteValueDictionary route)
//    {
//        return string.Format("YJQ_{0}_{1}_{2}", route["area"], route["controller"], _action ?? route["action"]);
//    }
    public String GetAuthorizeCode(HttpServletRequest request)
    {       
    	String url=request.getRequestURI();
    	String[] route = url.split("/");
    	//route = route.Skip(1).ToArray();
    	String action = route.length > 3 ? route[3] : "Get";
    	String controller = route.length > 2 ? route[2] : "Get";
    	String area = route.length > 1 ? route[1] : "Get";
        return PFDataHelper.FormatString("YJQ_{0}_{1}_{2}",area, controller,PFDataHelper.StringIsNullOrWhiteSpace(_action)? action:_action);
    }
}
